#include <iostream>
#include <list>
#include <functional>

using std::cout;
using std::endl;
using std::list;
/* using std::less; */

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

//自定义函数对象（仿函数）
template <typename T>
struct CompareList
{
    bool operator()(const T &lhs, const T &rhs) const
    {
        cout << "bool operator()(const T &, const T &) const" << endl;
        return lhs < rhs;
    }
};

void test()
{
    list<int> number = {1, 3, 5, 5, 9, 9, 8, 6, 2};
    display(number);

    cout << endl << "测试list的sort函数" << endl;
    /* number.sort();//默认情况，会按照从小到大的顺序进行排序 */
    /* std::less<int> les; */
    /* number.sort(std::less<int>()); */
    /* number.sort(les); */
    /* number.sort(std::greater<int>()); */
    number.sort(CompareList<int>());
    display(number);
}

void test2()
{
    list<int> number = {1, 3, 5, 5, 9, 9, 8, 6, 2, 5, 9, 5};
    display(number);

    cout << endl << "测试list的reverse函数" << endl;
    number.reverse();
    display(number);

    cout << endl << "测试list的unique函数" << endl;
    number.sort();
    number.unique();//需要先将元素进行排序，然后才能去除重复元素
    display(number);

    cout << endl << "测试list的merge函数" << endl;
    list<int> number2 = {11, 99, 88, 33, 7};
    number2.sort();
    display(number2);

    cout << endl << "先执行排序操作" << endl;
    number.sort(std::greater<int>());
    number2.sort(std::greater<int>());
    display(number);
    display(number2);
    //两个链表要进行merge的时候，需要先分别将两个链表进行从小
    //到大排序，然后再进行merge，否则就达不到合并后排序的效果
    number.merge(number2);
    display(number);
    display(number2);

    cout << endl << "测试splice函数" << endl;
    list<int> number3 = {111, 555, 777, 333, 666};
    display(number3);
    auto it = number.begin();
    ++it;
    ++it;
    cout << "*it = " << *it << endl;
    /* number.splice(it, number3); */
    /* display(number); */
    /* display(number3); */
    auto it2 = number3.begin();
    ++it2;
    cout << "*it2 = " << *it2 << endl;
    number.splice(it, number3, it2);
    display(number);
    display(number3);

    cout << endl << endl;
    it2 = number3.begin();
    ++it2;
    cout << "*it2 = " << *it2 << endl;
    auto it3 = number3.end();
    --it3;
    cout << "*it3 = " << *it3 << endl;
    number.splice(it, number3, it2, it3);//[it2, it3)
    display(number);
    display(number3);

    cout << endl << endl;
    auto it4 = number.begin();
    ++it4;
    ++it4;
    cout << "*it4 = " << *it4 << endl;
    auto it5 = number.end();
    --it5;
    --it5;
    cout << "*it5 = " << *it5 << endl;
    number.splice(it4, number, it5);
    display(number);
}

int main(int argc, char **argv)
{
    test2();
    return 0;
}

